<template>
	<!-- 原料仓库-无单出库池 -->
	<a-card :bordered="false">
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="7" :sm="8">
						<a-form-item label="物料">
							<a-input v-model="queryParam.materialName" placeholder="请输入物料" />
						</a-form-item>
					</a-col>
					<a-col :md="7" :sm="8">
						<a-form-item label="料号">
							<a-input v-model="queryParam.materialCode" placeholder="请输入料号" />
						</a-form-item>
					</a-col>
					<a-col :md="6" :sm="8">
						<a-form-item label="领用方">
							<a-select placeholder="全部" v-model="queryParam.classGroupId">
								<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
									{{ item.name }}
								</a-select-option>
							</a-select>
							<!-- <a-input v-model="queryParam.classGroupId" placeholder="请输入料号" /> -->
						</a-form-item>
					</a-col>
					<!-- <a-col :md="8" :sm="24">
            <a-form-item label="物料类型">
              <a-select :default-value="materialType" v-model="queryParam.materialType"
                        style="width: 120px">
                <a-select-option :value="item.id" v-for="(item, index) in materialTypeList">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->

					<a-col :md="3" :sm="24">
						<span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh()">查询</a-button>
							<a-button style="margin-left: 8px"
								@click="() => { queryParam.classGroupId = undefined; queryParam.materialCode = null; queryParam.materialName = null; $refs.table.refresh(true) }">重置</a-button>
						</span>
					</a-col>

					<!-- <a-col :md="24" :sm="24">
            <a-form-item label="供应商：">
              <FCOrgRadioGroup v-model="queryParam.orgIdSupplier"
                               :filter-types="[$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id,$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id]"/>
            </a-form-item>
          </a-col> -->

				</a-row>
			</a-form>
		</div>

		<div class="table-operator">
			<a-button type="primary"
				@click="$refs.simpleOrderAddForm.add({ orderType: ORDER_TYPE_ENUM.inOrder.id, selectedRows })" icon="plus"
				v-if="urlParam.poolType == ORDER_TYPE_ENUM.inOrder.id">入库
			</a-button>
			<a-button type="primary"
				@click="$refs.simpleOrderAddForm.add({ orderType: ORDER_TYPE_ENUM.outOrder.id, selectedRows })" icon="plus"
				v-if="urlParam.poolType == ORDER_TYPE_ENUM.outOrder.id">出库
			</a-button>
			<!-- <a-button type="primary"
				@click="$refs.simpleOrderAddForm.add({ orderType: ORDER_TYPE_ENUM.purchaseOrder.id, selectedRows, materialType, poolType: urlParam.poolType })"
				icon="plus" v-if="urlParam.poolType == ORDER_TYPE_ENUM.purchaseOrder.id">
				提交采购
			</a-button> -->
			<a-button type="primary"
				@click="$refs.simpleOrderAddForm1.add({ orderType: ORDER_TYPE_ENUM.purchaseOrder.id, selectedRows, materialType, poolType: urlParam.poolType })"
				icon="plus" v-if="urlParam.poolType == ORDER_TYPE_ENUM.purchaseOrder.id">
				提交采购申请
			</a-button>
			<!-- 无单出库池的按钮 -->
			<router-link :to="{ name: 'material_base', query: { viewState: 'material' } }"
				v-if="materialType == $businessEnum.MATERIAL_TYPE_ENUM.material.id">
				<a-button type="primary" icon="plus">新增原料</a-button>
			</router-link>
			<router-link :to="{ name: 'customized_base', query: { viewState: 'customized' } }"
				v-if="materialType == $businessEnum.MATERIAL_TYPE_ENUM.customized.id">
				<a-button type="primary" icon="plus">新增定制料</a-button>
			</router-link>
			<router-link :to="{ name: 'ems_matrial_product_base', query: { viewState: 'product' } }"
				v-if="materialType == $businessEnum.MATERIAL_TYPE_ENUM.product.id">
				<a-button type="primary" icon="plus">新增产品</a-button>
			</router-link>
			<router-link :to="{ name: 'ems_matrial_cable_base', query: { viewState: 'cable' } }"
				v-if="materialType == $businessEnum.MATERIAL_TYPE_ENUM.cable.id">
				<a-button type="primary" icon="plus">新增线缆</a-button>
			</router-link>
			<router-link :to="{ name: 'ems_matrial_packing_base', query: { viewState: 'packing' } }"
				v-if="materialType == $businessEnum.MATERIAL_TYPE_ENUM.packing.id">
				<a-button type="primary" icon="plus">新增包材</a-button>
			</router-link>
		</div>
		<!-- 22--{{ selectedRows }} -->
		<div style="display: flex;align-items:flex-end;justify-content: space-between;">
			<div class="selectText">
				<span>当前表格已选中 <span class="bold">{{ selectedRows.length }}</span> 项</span>
				<span style="cursor: pointer;" @click="clearSelect">清除</span>
			</div>
		</div>
		<!-- 22--{{ selectedRows.map(i=>i.materialPoolId) }}
    33--{{ isAllSelect }} -->
		<s-table ref="table" size="default"
			:columns="(managerOrFinance() || (isJSYRole() && materialType == '1843830985384407041')) ? columns : columns1"
			:data="getList" :alert="true">
			<!-- 全选按钮 -->
			<span slot="allSelectBtn">
				<div class="select-btn" :class="{
					'select-btn__selected': isAllSelect == 3,
					'select-btn__half': isAllSelect == 2,
					'select-btn__disabled': false,
				}" @click="handleChangeAllSelect(isAllSelect == 3 ? 1 : 3)"></div>
			</span>
			<!-- 普通选择按钮 -->
			<span slot="selectBtn" slot-scope="text, record">
				<!-- 采购池-提交采购 才需要禁用 -->
				<div class="select-btn" :class="{
					'select-btn__selected': selectedRows.some(item => item.materialPoolId == record.materialPoolId),
					'select-btn__disabled': urlParam.poolType == ORDER_TYPE_ENUM.purchaseOrder.id && selectedRows.length > 0 && selectedRows[0].orgIdSupplier !== record.orgIdSupplier,
				}" @click="urlParam.poolType == ORDER_TYPE_ENUM.purchaseOrder.id && selectedRows.length > 0 && selectedRows[0].orgIdSupplier !== record.orgIdSupplier ? '' : handleClickSelectBtn(record)">
				</div>
			</span>
			<span slot="action" slot-scope="text, record">
				<a @click="$refs.editForm.edit(record)">编辑</a>
				<a-divider type="vertical" />
				<!--        <a-dropdown>-->
				<!--          <a class="ant-dropdown-link"> 更多 <a-icon type="down"/></a>-->
				<!--          <a-menu slot="overlay">-->
				<!--            <a-menu-item>-->
				<a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
					<a>删除</a>
				</a-popconfirm>
				<!--            </a-menu-item>-->
				<!--          </a-menu>-->
				<!--        </a-dropdown>-->
			</span>

			<!-- <span slot="image" slot-scope="text">
				<image-preview :images="text" />
			</span> -->
			<span slot="image" slot-scope="text,record">
				<image-preview1 :images="text" :imageUrl="record.imageUrl" />
			</span>
		</s-table>

		<add-form ref="addForm" @ok="handleOk" />
		<edit-form ref="editForm" @ok="handleOk" />
		<simple-order-add-form ref="simpleOrderAddForm" @ok="handleOk" />
		<simple-order-add-form1 ref="simpleOrderAddForm1" @ok="handleOk" />
	</a-card>
</template>

<script>
import { STable } from '@/components'
import { del, page } from '@/api/modular/main/emsmaterialpool/emsMaterialPoolManage'
import addForm from './emsMaterialPoolAddForm'
import editForm from './emsMaterialPoolEditForm'
import simpleOrderAddForm from '../emsorder/emsSimpleOrderAddForm'
import simpleOrderAddForm1 from './emsSimpleOrderAddForm1'
import { getUrlParam, MATERIAL_TYPE_ENUM, ORDER_TYPE_ENUM } from '@/utils/util'
import { list as emsOrgList } from '@/api/modular/main/emsorg/emsOrgManage'
import FCOrgRadioGroup from '@/components/FcOrgRadioGroup/FCOrgRadioGroup'

import { page as teamPage } from '@/api/modular/main/classGroup/classGroup'

export default {
	components: {
		FCOrgRadioGroup,
		STable,
		addForm,
		editForm,
		simpleOrderAddForm,
		simpleOrderAddForm1
	},

	data() {
		return {
			queryParam: {},  // 查询参数
			isAllSelect: 1,  //全选按钮状态： 1未选 2半选 3全选
			tableData: [],  //用来给全选按钮用
			columns: [       // 表头
				{
					width: '80px',
					slots: { title: 'allSelectBtn' },
					scopedSlots: { customRender: 'selectBtn' }
				},
				{
					title: '序号', width: '80px',
					dataIndex: 'materialId',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '物料',
					dataIndex: 'materialName'
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber'
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '库存',
					dataIndex: 'inventoryNumber'
				},
				{
					title: '领用方',
					dataIndex: 'classGroupName'
				},
				{
					title: '供应商',
					dataIndex: 'orgIdSupplierName'
				},
				{
					title: '数量',
					dataIndex: 'number'
				},
				{
					title: '单价',
					dataIndex: 'costPrice'
				},
				{
					title: '备注',
					dataIndex: 'remark'
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '150px',
					scopedSlots: { customRender: 'action' }
				}
			],
			columns1: [
				{
					width: '80px',
					slots: { title: 'allSelectBtn' },
					scopedSlots: { customRender: 'selectBtn' }
				},    // 表头
				{
					title: '序号', width: '80px',
					dataIndex: 'materialId',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '物料',
					dataIndex: 'materialName'
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber'
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '库存',
					dataIndex: 'inventoryNumber'
				},
				// {
				//   title: '供应商',
				//   dataIndex: 'orgIdSupplierName'
				// },
				{
					title: '领用方',
					dataIndex: 'classGroupName'
				},
				{
					title: '数量',
					dataIndex: 'number'
				},
				// {
				//   title: '单价',
				//   dataIndex: 'costPrice'
				// },
				{
					title: '备注',
					dataIndex: 'remark'
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '150px',
					scopedSlots: { customRender: 'action' }
				}
			],
			// 加载数据方法 必须为 Promise 对象
			getList: parameter => {
				let poolType = this.urlParam.poolType
				// let materialType = this.queryParam.materialType
				return page(Object.assign(parameter, this.queryParam, { poolType })).then((res) => {
					this.tableData = res.data.rows
					// this.tableData.forEach(item => {
					//   let have = this.selectedRows.some(i=>i.materialPoolId==item.materialPoolId)
					//   if(!have){
					//     this.selectedRows.push(item)
					//   }
					// })
					let isSelectArr = []
					let tempRows = this.selectedRows.length ? this.selectedRows.map(i => i.materialPoolId) : []
					// 判断是否全选
					this.tableData.forEach(item => {
						isSelectArr.push(tempRows.includes(item.materialPoolId))
					})

					if (isSelectArr.every(i => i) && this.tableData.length > 0) {
						this.isAllSelect = 3
					} else if ((isSelectArr.some(i => i) && (isSelectArr.some(i => !i)))) {
						this.isAllSelect = 2
					} else if (isSelectArr.every(i => !i)) {
						this.isAllSelect = 1
					}


					return res.data
				})
			},
			selectedRows: [],
			suppliers: [],
			teamList: [],
		}
	},
	computed: {
		// isAllSelect: 2,  //全选按钮状态： 1未选 2半选 3全选
		// isAllSelect() {
		//   // if(){

		//   // } else if(){

		//   // } else {

		//   // }
		//   return 2
		// },
		urlParam() {
			return getUrlParam(this.$route.path)
		},
		poolType() {
			return this.urlParam.poolType;
		},
		materialType() {
			return this.urlParam.materialType;
		},
		ORDER_TYPE_ENUM() {
			return ORDER_TYPE_ENUM;
		},
		materialTypeList() {
			let value = [{ id: '', name: '全部', code: 'all' }]
			for (const key in MATERIAL_TYPE_ENUM) {
				value.push(MATERIAL_TYPE_ENUM[key])
			}
			return value
		},
	},
	watch: {
		'$route.path': function () {
			console.log(`watch`)
			this.queryParam.materialType = this.urlParam.materialType
			// this.queryParam.materialName = undefined;
			// this.queryParam.materialCode = undefined;
			// this.queryParam.classGroupId = undefined;
			setTimeout(() => {
				this.$refs.table.refresh(true)
				this.selectedRows.length = []
			}, 100)
		}
	},
	created() {
		this.queryParam = { materialType: this.urlParam.materialType }
		this.getSuppliers();
		this.getTeamList();
	},
	methods: {
		// 全选按钮事件
		handleChangeAllSelect(value) {
			this.isAllSelect = value
			if (value == 3) {  //全选
				if (this.selectedRows.length) {
					let orgIdSupplier = this.selectedRows[0].orgIdSupplier
					this.selectedRows = []
					this.tableData.forEach(item => {
						if (orgIdSupplier === item.orgIdSupplier) {
							this.selectedRows.push(item)
						}
					})
				} else {
					this.tableData.forEach(item => {
						let have = this.selectedRows.some(i => i.orgIdSupplier !== item.orgIdSupplier)
						if (!have) {
							this.selectedRows.push(item)
						}
					})
				}

			} else if (value == 1) {  //取消全选
				this.tableData.forEach(item => {
					this.selectedRows.forEach(i => {
						if (i.materialPoolId == item.materialPoolId) {
							this.selectedRows.splice(this.selectedRows.indexOf(i), 1)
						} else {
						}
					})
				})
			}

			console.log('value,', value, this.selectedRows)

		},
		//获取领用方
		getTeamList() {
			teamPage({
				pageSize: -1,
				status: 0
			}).then(res => {
				this.teamList = res.data.rows;
			})
		},
		// 表格选择按钮点击事件
		handleClickSelectBtn(record) {
			let i = this.selectedRows.findIndex(item => item.materialPoolId === record.materialPoolId)
			if (i == -1) {
				this.selectedRows.push(record)
			} else {
				this.selectedRows.splice(i, 1)
			}
			let isSelectArr = []
			let tempRows = this.selectedRows.length ? this.selectedRows.map(i => i.materialPoolId) : []
			// 判断是否全选
			this.tableData.forEach(item => {
				isSelectArr.push(tempRows.includes(item.materialPoolId))
			})
			if (isSelectArr.every(i => i) && this.tableData.length > 0) {
				this.isAllSelect = 3
			} else if ((isSelectArr.some(i => i) && (isSelectArr.some(i => !i)))) {
				this.isAllSelect = 2
			} else if (isSelectArr.every(i => !i)) {
				this.isAllSelect = 1
			}
		},
		// 清除选中
		clearSelect() {
			this.selectedRows = []
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		handleOk() {
			this.$refs.table.refresh()
			this.selectedRows.length = 0
		},
		// onSelectChange(selectedRowKeys, selectedRows) {
		//   this.selectedRowKeys = selectedRowKeys
		//   this.selectedRows = selectedRows
		// },
		// handleMaterialTypeSelectChange(value) {
		//   // this.queryParam = Object.assign({}, this.queryParam, {materialType: value})
		//   this.queryParam.materialType = value
		// },
		getSuppliers() {
			emsOrgList({
				pid: '1473297518794452994',
				unitRanId: this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id
			}).then((res) => {
				this.suppliers = res.data
			})
		},
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
